<!DOCTYPE html>
<html lang="zh-Cn">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <p class="p"></p>
    <button onclick="startWorker()">开启线程</button>
    <button onclick="stopWorker()">停止线程</button>
  </body>
  <script>
    let worker
    function startWorker() {
      if (typeof Worker !== 'undefined') {
        if (typeof worker == 'undefined') {
          worker = new Worker('./worker.js')
        }
        worker.onmessage = function (event) {
          document.querySelector(
            '.p'
          ).innerText = `接收到另一个线程的数据为：${event.data}`
        }
      } else {
        document.querySelector('.p').innerText = '当前浏览器不支持多线程'
      }
    }

    //停止线程
    function stopWorker() {
      if (typeof worker !== 'undefined') {
        worker.terminate()
        worker = undefined
      }
    }
    // stopWorker()
  </script>
</html>
